import 'dart:io';
import 'dart:convert';

Future<void> fileReadDemo() async {
  var config = File('config.txt');
  try {
    // 读取整个文件为字符串
    var stringContents = await config.readAsString();
    print('The file is ${stringContents.length} characters long.');

    // 读取每一行为字符串
    var lines = await config.readAsLines();
    print('The file is ${lines.length} lines long.');

    // 读取为字节
    var contents = await config.readAsBytes();
    print('The file is ${contents.length} bytes long.');
  } catch (e) {
    print('fileReadDemo error: $e');
  }
}

Future<void> fileStreamDemo() async {
  var config = File('config.txt');
  try {
    Stream<List<int>> inputStream = config.openRead();
    var lines = utf8.decoder.bind(inputStream).transform(const LineSplitter());
    await for (final line in lines) {
      print('Got ${line.length} characters from stream');
    }
    print('file is now closed');
  } catch (e) {
    print('fileStreamDemo error: $e');
  }
}

Future<void> fileWriteDemo() async {
  try {
    var logFile = File('log.txt');
    var sink = logFile.openWrite();
    sink.write('FILE ACCESSED ${DateTime.now()}\n');
    await sink.flush();
    await sink.close();
    // 追加写入
    var sink2 = logFile.openWrite(mode: FileMode.append);
    sink2.write('APPEND LOG ${DateTime.now()}\n');
    await sink2.flush();
    await sink2.close();
  } catch (e) {
    print('fileWriteDemo error: $e');
  }
}

Future<void> dirListDemo() async {
  var dir = Directory('tmp');
  try {
    var dirList = dir.list();
    await for (final FileSystemEntity f in dirList) {
      if (f is File) {
        print('Found file ${f.path}');
      } else if (f is Directory) {
        print('Found dir ${f.path}');
      }
    }
  } catch (e) {
    print('dirListDemo error: $e');
  }
}

// HttpServer 相关代码需要特殊环境，已注释
// Future<void> httpServerDemo() async {
//   final requests = await HttpServer.bind('localhost', 8888);
//   await for (final request in requests) {
//     processRequest(request);
//   }
// }
// void processRequest(HttpRequest request) {
//   print('Got request for \\${request.uri.path}');
//   final response = request.response;
//   if (request.uri.path == '/dart') {
//     response
//       ..headers.contentType = ContentType('text', 'plain')
//       ..write('Hello from the server');
//   } else {
//     response.statusCode = HttpStatus.notFound;
//   }
//   response.close();
// }

void main() async {
  print('--- 文件读取演示 ---');
  await fileReadDemo();
  print('--- 文件流读取演示 ---');
  await fileStreamDemo();
  print('--- 文件写入演示 ---');
  await fileWriteDemo();
  print('--- 目录遍历演示 ---');
  await dirListDemo();
  print('全部IO操作演示结束');
}